package com.llsydn.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2018/9/27 16:34
 */
public class CommonUtils {
    public static final String PROJECT_CHARSET = "UTF-8";
    public static final String WEB_INF = "/WEB_INF";
    public static final String BUILD_CLASS = "/buildClass";
    public static final String STRING_VALUE__BACKSLASH = "\\";
    public static final String SLASH = "/";

    /**
     * 获取项目路径(例如：d:/folderPath/projectName，注意：最后是没有/的。)
     *
     * @return
     */
    public static String getProjectPath() {
        String projectPath = "";
        try {
            String tempPath = CommonUtils.class.getClassLoader().getResource("").getPath();
            if (tempPath.indexOf(".jar") > -1) {
                return tempPath.substring(6, tempPath.indexOf("!/"));
            }
            if (tempPath.length() > 0) {
                tempPath = tempPath.substring(1, tempPath.length());
                if (tempPath.indexOf(STRING_VALUE__BACKSLASH) > -1) {
                    tempPath = tempPath.replace("\\", "/");
                }
            }
            File file = new File(tempPath);
            if (file.exists()) {
                projectPath = file.getAbsolutePath();
                if (projectPath.indexOf(STRING_VALUE__BACKSLASH) > -1) {
                    projectPath = projectPath.replace("\\", "/");
                }
            } else {
                projectPath = file.getPath();
                if (projectPath.indexOf(STRING_VALUE__BACKSLASH) > -1) {
                    projectPath = projectPath.replace("\\", "/");
                }
                projectPath = "/" + projectPath;
            }
            try {
                projectPath = URLDecoder.decode(projectPath, PROJECT_CHARSET);
            } catch (UnsupportedEncodingException e) {
                System.out.println("获取项目路径时URL解码时程序出错！");
                e.printStackTrace();
            }
            if (projectPath.indexOf(WEB_INF) > -1) {
                projectPath = projectPath.substring(0, projectPath.indexOf("/WEB-INF"));
            }
            if (projectPath.indexOf(BUILD_CLASS) > -1) {
                projectPath = projectPath.substring(0, projectPath.indexOf("/buildClass")) + "/WebRoot";
            }
            if (projectPath.endsWith(SLASH)) {
                projectPath = projectPath.substring(0, projectPath.length() - 1);
            }
        } catch (Exception e) {
            System.out.println("获取项目路径时程序出错！");
            e.printStackTrace();
        }
        return projectPath;
    }
}
